import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';

//封装图片加载控件，增加图片加载失败时加载默认图片
class ImageWidget extends StatefulWidget {
  ImageWidget(
      {@required this.url, this.fit, this.w, this.h, this.defImagePath = ""});
  BoxFit fit;
  final String url;
  final double w;
  final double h;
  final String defImagePath;

  @override
  State<StatefulWidget> createState() {
    return _StateImageWidget();
  }
}

class _StateImageWidget extends State<ImageWidget> {
  var _image;

  @override
  void initState() {
    super.initState();
    _image = Image.asset(
      widget.url,
      width: widget.w,
      height: widget.h,
      fit: widget.fit,
    );
    var resolve = _image.image.resolve(ImageConfiguration.empty);
    resolve.addListener(ImageStreamListener((_, __) {
      //加载成功
    }, onError: (dynamic exception, StackTrace stackTrace) {
      //加载失败
      setState(() {
        _image = CachedNetworkImage(
          imageUrl: widget.defImagePath,
          fit: widget.fit,
          placeholder: (context, url) => new Container(
            child: new Center(
              child: new CircularProgressIndicator(),
            ),
          ),
        );
      });
    }));
  }

  @override
  Widget build(BuildContext context) {
    return _image;
  }
}
